#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.shortcuts import render,render_to_response,redirect,RequestContext


# Create your views here.

def login(request,*args,**kwargs):
    if request.method == 'POST':
        user = request.POST.get('username',None)
        pwd = request.POST.get('password',None)
        if user == 'tom' and pwd == '123':
            #request.session['is_login'] = True  # 设置过期时间，或者主动销毁，则值消失。 其他函数都可以使用，相当于一个全局变量。
            request.session['is_login'] = {'user':user} # 操作数据库，设置session值
            return redirect('/session/index/')
        else:
            return  render_to_response('session/login.html',{'msg':'用户名或密码错误'},context_instance=RequestContext(request))    #将请求request当做参数传递给RequestContext
    return render_to_response('session/login.html',context_instance=RequestContext(request))

def index(request,*args,**kwargs):
    '''
    is_login = request.session.get('is_login',None)   # 访问需要登录的页面，先检测会话，判断是否登录
    if is_login:
        return render_to_response('session/index.html',context_instance=RequestContext(request))
    else:
        return redirect('/session/login/')
    '''
    user_dict = request.session.get('is_login',None)    # 操作数据库，获取session值
    if user_dict:
        return render_to_response('session/index.html',{'username':user_dict.user},context_instance=RequestContext(request))
    else:
        return redirect('/session/login/')

def logout(request,*args,**kwargs):
    del request.session['is_login']     # 操作数据库，销毁session
    return redirect('/session/login')